package com.example.workrecord.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.workrecord.config.WebLog;
import com.example.workrecord.entity.AuthInfo;
import com.example.workrecord.entity.CorpUserDetail;
import com.example.workrecord.exption.BizException;
import com.example.workrecord.service.AuthHelper;
import com.example.workrecord.util.AliYunOssPrivateUtil;
import com.example.workrecord.util.AliYunOssUtil;
import com.example.workrecord.util.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@RestController
@Api(value = "logindingding", description = "登陆接口", consumes = "application/json;charset=UTF-8")
@RequestMapping(value = "/logindingding")
public class LoginController  extends BaseController {

    @Autowired
    private AuthHelper authHelper;
    @PostMapping("/login")
    @ResponseBody
    @WebLog(description = "免登接口")
    @ApiOperation(value = "免登接口，提交信息包含corpid与appkey", notes = "{}")
    public Result login(@RequestBody JSONObject res ){
        CorpUserDetail userDetail;
        try {
            checkNull(res,"参数不能为空");
            AuthInfo authInfo=JSONObject.parseObject(res.toJSONString(),AuthInfo.class);
            userDetail=authHelper.login(authInfo);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
        return Result.success(userDetail);
    }



    @PostMapping("/fileUpload")
    @ResponseBody
    @WebLog(description = "用户图片上传")
    @ApiOperation(value = "用户图片上传", notes = "{\"fileList\":\"文件路径\"}")
    public Result updateDeptManager(HttpServletRequest request,@RequestParam(value="fileList", required=false) List<MultipartFile> list ){
        List<String> urlList=new ArrayList<>();
        try{
//            CorpUserDetail user = getUserInfo(request);
//            if(null == user || user.getUserid().equals("")){
//                return Result.error("用户信息未找到，请重新登陆");
//            }
            String returnUrl=request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/upload/imgs/";
            String path=request.getSession().getServletContext().getRealPath("upload/imgs");
            System.out.println(path);
            if(null != list&& list.size()>0){
                for(MultipartFile multipartFile:list){
                    UUID uuid=UUID.randomUUID();
                    if (null == multipartFile || "".equals(multipartFile)) {
                        throw new BizException("上传文件不可为空。请检查！");
                    }
                    String originalFilename=multipartFile.getOriginalFilename();
                    String extendName=originalFilename.substring(originalFilename.lastIndexOf("."), originalFilename.length());
                    String fileName=uuid.toString() + extendName;
                    File dir=new File(path, fileName);
                    File filepath=new File(path);
                    if (!filepath.exists()) {
                        filepath.mkdirs();
                    }
                    multipartFile.transferTo(dir);
                   String url=returnUrl + fileName;
                    urlList.add(url);
                }
            }

        }catch (Exception e){
            return Result.error(e.getMessage());
        }
        return Result.success(urlList);
    }

    /**
     *      * 判断是否是图片 请选择格式为jpeg/jpg/pjpeg/png/x-png/gif的图片!
     *      * @param photoName
     *      * @return
     *      
     */
    private boolean isPhoto(String photoName) {
        String imgExt="jpg|jpeg|png|bmp|gif|pjpeg|x-png|GIF|JPG|PNG|JPEG|BMP|PJPEG|X-PNG";
        if (imgExt.indexOf(photoName) >= 0) {
            return true;
        }
        return false;
    }

    @PostMapping("/fileUploadOss")
    @ResponseBody
    @WebLog(description = "文件上传至公共OSS")
    @ApiOperation(value = "文件上传至公共OSS", notes = "{\"file_path\":\"文件路径\"}")
    public Result fileUpload(HttpServletRequest request,@RequestParam(value="fileList", required=false) MultipartFile[] list ) {
        List<String> nameList=new ArrayList<>();
        try {
//            CorpUserDetail user = getUserInfo(request);
//            if(null == user || user.getUserid().equals("")){
//                return Result.error("用户信息未找到，请重新登陆");
//            }

            if (null  == list) {
                throw new BizException("上传文件不能为空");
            }
            for(MultipartFile multipartFile:list){
                String  newName=AliYunOssPrivateUtil.fileUpload(multipartFile);
                nameList.add(newName);
            }
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
        return Result.success(nameList);
    }


    @PostMapping("/byteUpload")
    @ResponseBody
    @WebLog(description = "base64上传至公共OSS")
    @ApiOperation(value = "base64上传至公共OSS",notes = "{\"fileName\":\"文件名称\",\"img64Byte\":\"base64位字符串\"}")
    public Result byteUpload(HttpServletRequest request,@RequestBody JSONObject res) {
        String newName=null;
        try {

            CorpUserDetail user = getUserInfo(request);
            if(null == user || user.getUserid().equals("")){
                return Result.error("用户信息未找到，请重新登陆");
            }
           checkNull(res,"文件上传不能为空");
            String fileName = res.get("fileName").toString();
            String img64Byte = res.get("img64Byte").toString();
            newName=AliYunOssUtil.byteUpload(fileName, img64Byte, "hzhw");
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
        return Result.success(newName);
    }

    @PostMapping("/htmlfileUpload")
    @ResponseBody
    @WebLog(description = "富文本文件上传至公共OSS")
    @ApiOperation(value = "富文本文件上传至公共OSS", notes = "{\"file_path\":\"文件路径\"}")
    public Result htmlfileUpload(HttpServletRequest request,@RequestParam(value ="file_path", required = false) MultipartFile multipartFile) {

        String newName=null;
        try {
            CorpUserDetail user = getUserInfo(request);
            if(null == user || user.getUserid().equals("")){
                return Result.error("用户信息未找到，请重新登陆");
            }
            if (multipartFile == null) {
                throw new BizException("上传文件不能为空");
            }
            newName="https://hzhw.oss-cn-hangzhou.aliyuncs.com/" + AliYunOssUtil.fileUpload(multipartFile, "hzhw");
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
        return Result.success(newName);
    }


//    @PostMapping("/fileDownload")
//    @ResponseBody
//    @WebLog(description = "公共OSS文件下载")
//    @ApiOperation(value = "公共OSS文件下载",  notes = "{\"fileType\":\"文件路径\",\"file_name\":\"文件名称\"}")
//    public Result fileDownload(@RequestBody JSONObject res) {
//        try {
//            JSONObject obj=  AliYunOssUtil.fileDowload(res.getString("file_name"),res.getString("fileType"));
//            return Result.success(obj);
//        } catch (Exception e) {
//            return Result.error(e.getMessage());
//        }
//    }
//
//


}
